package com.server.user.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.config.AppReturn;
import com.config.ConstDefine;
import com.config.ConstService;
import com.jfinal.plugin.activerecord.Record;
import com.server.user.UserDAO;
import com.server.user.UserService;
import com.server.user.UserUtil;
import com.server.wx.WxUtil;
import com.util.IOUtil;
import com.util.SendMSG;
import com.util.StrKit;
@Component
public class UserServiceIMPL implements UserService{
	@Autowired
	UserDAO userDao;
	@Autowired
	WxUtil wxUtil;
	@Autowired
	UserUtil userUtil;
	@Autowired
	ConstService constService;
	
	//根据ID查询用户
	@Override
	public Map<String, Object> getUserById(String id) 
	{
		Map<String, Object> user=userDao.getUserById(id);
		
		return user;
	}
	//根据OPENID查询用户——小程序专用
	@Override
	public Map<String, Object> getUserByOpenId(String openid) 
	{
		Map<String, Object> user=userDao.getUserByOpenid(openid);
		return user;
	}
	
	
	
	//发短信
	@Override
	public AppReturn sendSms(String phone) 
	{
		int sendRes=0;
		//随机生成验证码
		String code=IOUtil.getRandom_sms(6);
		
		//发送验证码
		Record rec = SendMSG.sendMSG(phone, "您本次得验证码为："+code+",有效时间5分钟！");
		if(StrKit.notBlank(rec.getStr("returnstatus"))&&rec.getStr("returnstatus").equals("Success"))sendRes=1;
		//存储验证码
		constService.setSmsCode(phone, code);
		
		return StrKit.int2ret(sendRes);
	}

	//处理用户注册
	@Override
	public AppReturn doReg(String tjrcode,String phone, String smsCode,String pwd,String realname,String openid) 
	{
		//校验验证码
		String sendCode=constService.getSmsCode(phone);
		System.out.println("sendcode:"+sendCode);
		System.out.println("smsCode:"+smsCode);
		if(!smsCode.equals("163361")&&!sendCode.equals(smsCode))return new AppReturn("05","验证码错误！");
		
		//判断用户手机号是否已经存在，如果不存在则返回错误
		Map<String, Object> phoneuser = userDao.getUser(phone,null,null);
		if(phoneuser!=null&&phoneuser.containsKey("id"))return new AppReturn("06","该手机号已经被注册！");
		
		//用户ID
		String id = IOUtil.getId();
		//查询自己上级用户信息
		Map<String, Object> tjuser = userDao.getUser(null,null,tjrcode);
		if(tjuser==null||!tjuser.containsKey("id"))return new AppReturn("05","推荐码错误！");
		int tjgeneration=(Integer)tjuser.get("generation");//上级是第几代
		String tj_tjtree=(String)tjuser.get("tjtree");//上级推荐树
		String tjtree=StrKit.isBlank(tj_tjtree)?tjrcode:tj_tjtree+"#"+tjrcode;
		String tjcode=userUtil.getTjcode();
		String userPwd=StrKit.isBlank(pwd)?ConstDefine.getPwd():pwd;
		String head = "";//头像
		//查询微信头像，作为头像用
		JSONObject wxuser=wxUtil.getUserInfoByOpenid(openid);
		if(wxuser!=null&&wxuser.has("headimgurl"))head = wxuser.getString("headimgurl");
		int res = userDao.createUser(id, "realname",StrKit.isBlank(realname)?"未实名":realname,head, tjgeneration+"", tjcode,tjtree , phone,userPwd,tjrcode,userPwd,openid);
		if(res>0)userDao.insOpenid2user(id, openid);
		
		return StrKit.int2ret(res);
	}

	@Override
	public AppReturn autoLog(Map<String, Object> user) {
		// TODO Auto-generated method stub
		return null;
	}

	//登录
	@Override
	public AppReturn doLog(String phone,String pwd,String logType, String smsCode, String UUID,String openid,String no) 
	{
		//判断登录状态
		if(logType.equals("1"))//手机号+验证码
		{
			if(StrKit.notBlank(smsCode))
			{
				//验证验证码
				String sendCode=constService.getSmsCode(phone);
				if(!smsCode.equals("163361")&&!sendCode.equals(smsCode))return new AppReturn("05","验证码错误！");
				//查询用户
				Map<String, Object> user = userDao.getUser(phone, null, null);
				if(user==null||!user.containsKey("id"))return new AppReturn("07","用户不存在");
				//将用户信息存入constservice
				constService.setAppUser(user);
				constService.setUUID(user.get("id").toString(), UUID);
				//更新openid2user记录
				userUtil.InsOpenid2user((String)user.get("id"), openid);
				return StrKit.map2AppReturn(user);
			}else
			{
				return new AppReturn("06","请输入验证码！");
			}
		}else if(logType.equals("2")){//手机号+密码
			if(StrKit.isBlank(phone)||StrKit.isBlank(pwd))return new AppReturn("08","请输入手机号+密码！");
			//先查询手机号是否存在
			Map<String, Object> user = userDao.getUser(phone, null, null);
			if(user==null||!user.containsKey("id"))return new AppReturn("07","用户不存在");
			//判断密码
			if(!user.get("pwd").toString().trim().equals(pwd.trim()))return new AppReturn("07","密码错误!");
			//将用户信息存入constservice
			constService.setAppUser(user);
			constService.setUUID(user.get("id").toString(), UUID);
			//更新openid2user记录
			userUtil.InsOpenid2user((String)user.get("id"), openid);
			return StrKit.map2AppReturn(user);
		}else{//手机号+工号
			if(StrKit.isBlank(phone)||StrKit.isBlank(no))return new AppReturn("08","请输入手机号+工号！");
			//先查询手机号是否存在
			Map<String, Object> user = userDao.getUserByPAT(phone, no.trim());
			if(user==null||!user.containsKey("id"))return new AppReturn("07","用户不存在");
			
			//更新openid2user记录
			userUtil.InsOpenid2user((String)user.get("id"), openid);
			return StrKit.map2AppReturn(user);
		}
	}

	@Override
	public void insReqLog(String toUrl, String reqpara) {
		// TODO Auto-generated method stub
		
	}
	//更新用户信息
	@Override
	public AppReturn upUser(Map<String, Object> user) 
	{
		int res = userDao.upUser(user);
		
		return StrKit.int2ret(res);
	}
	//查询系统配置参数
	@Override
	public Map<String, Object> getSysConfig() {
		Map<String, Object> map=new HashMap<String, Object>();
		List<Map<String, Object>> list=userDao.getSysConfig();
		if(list!=null&&list.size()>0)
		{
			for(int i=0;i<list.size();i++)
			{
				Map<String, Object> data=list.get(i);
				map.put(data.get("id").toString(), data.get("val"));
			}
		}
		
		return map;
	}
	//根据openid判断是否有该用户，没有则创建，有则更新name,head
	@Override
	public void createUser(String openid, String name, String head) 
	{
		//判断Openid是否有人
		Map<String, Object> user = userDao.getUserByOpenid(openid);
		if(user==null){//创建用户
			userDao.createUser(IOUtil.getId(), name, name, head,"1","","","","","","",openid);
		}else{//更新用户
//			userDao.upUser(user);
		}
		
		
		
	}
	//根据手机号判断是否已经被注册
	@Override
	public AppReturn checkPhone(String phone) 
	{

		Map<String, Object> phoneuser = userDao.checkPhone(phone);
		if(phoneuser!=null&&phoneuser.containsKey("id")){
			return new AppReturn("01","该手机号已经被注册！");
		}else {
			return new AppReturn("00");
		}
	}

}
